﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Controls.Primitives;
using Microsoft.Practices.ServiceLocation;
using Utils.EventAggregator;
using GameStudio.IDE.Common.Events;
using GameStudio.IDE.Common;

namespace GameStudio.IDE.Controls
{
    [TemplatePart(Name = "treeView", Type = typeof(TreeView))]

    public class SolutionExplorerControl : Control
    {
        TreeView treeView;
        TreeViewItem treeViewClasses;
        TreeViewItem treeViewModels;

        public SolutionExplorerControl()
        {
            var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
            eventAggregator.GetEvent<AddNewItemEvent>().Subscribe(OnAddNewItem);

        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            treeView = (TreeView)GetTemplateChild("treeView");

            treeViewClasses = new TreeViewItem();
            treeViewClasses.Header = "Classes";
            treeView.Items.Add(treeViewClasses);

            treeViewModels = new TreeViewItem();
            treeViewModels.Header = "Models";
            treeView.Items.Add(treeViewModels);

            treeView.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(treeView_SelectedItemChanged);
        }

        void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
            eventAggregator.GetEvent<SelectItemSolutionExplorerEvent>().Publish(treeView.SelectedItem.ToString());
        }

        private void OnAddNewItem(Item item)
        {
            if (item.Type == "Model")
            {
                treeViewModels.Items.Add(item.Name);                
            }
            else if (item.Type == "Class")
            {
                treeViewClasses.Items.Add(item.Name);
            }
        }
    }
}
